import AlertFill from "@/assets/image/icons/alert-fill.svg";
import Resend from "@/assets/image/icons/resend.svg";
import Sound from "@/assets/image/icons/sound.svg";
import Time from "@/assets/image/icons/time.svg";
import useStore from "@/store/configStore";
import { ProFormCheckbox, ProFormText } from "@ant-design/pro-components";
import CountDown from "ant-design-pro/lib/CountDown";
import { Button, Descriptions, message, Space } from "antd";
import { useEffect, useState } from "react";
import { history, useLocation } from "umi";

import { StyledAgree, StyledCancel } from "@/components/button";
import { StyledTextAlign } from "@/components/common-styled";
import CustomModal from "@/components/customModal";
import { CustomSubTitle, CustomTitle } from "@/components/customTitle";
import { StyledDivider } from "@/components/divider";
import { ContentBorder, PaddingContent } from "@/components/page-padding";
import { getCreateBooking, getGenerateCodeAndPic } from "@/services/carPark";
import useParkStore from "@/store/parkStore";
import userStore from "@/store/userStore";
import "./index.less";

const LabelStyle = {
  fontFamily: "Roboto",
  fontSize: "14px",
  fontWeight: "400",
  lineHeight: "21px",
  color: "#696767",
  // marginTop: "24px",
  paddingBottom: "0px",
};

const ContentStyle = {
  fontFamily: "Roboto",
  fontSize: "16px",
  fontWeight: "400",
  lineHeight: "24px",
  color: "#202020",
  //marginTop: "8px",
};

export const CountDownSytle: React.CSSProperties = {
  fontFamily: "Roboto",
  fontSize: "16px",
  fontWeight: "400",
  lineHeight: "24px",
  textAlign: "left",
  color: "#7A6145",
};

export const targetTime = new Date().getTime() + 15 * 60 * 1000;
export const formatTime = (currentTime: any) => {
  const minutes = Math.floor(currentTime / 1000 / 60);
  const remainingSeconds = Math.floor(currentTime / 1000) % 60;
  return `${minutes}:${remainingSeconds < 10 ? "0" : ""}${remainingSeconds}`;
};

const PaymentInfo = () => {
  const { login } = useStore();
  const location = useLocation();
  // get query params
  const queryParams = new URLSearchParams(location.search);
  //Pay Fail modal status，fail show Payment Failure modal, timeout show Session Timeout modal
  const isShowPayFailModal = queryParams.get("isShowPayFailModal");
  //存在daily payment info monthly payment info
  const { price, pymPrice, dpppPrice, period, bookingDataRes } = useParkStore();
  console.log(bookingDataRes, "bookingDataRes");
  const { userId } = userStore();
  const calculatedCost = (Number(price) - Number(dpppPrice)) * period;
  // confirm pay modal
  const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
  // Payment Failure modal
  const [isPayFailModalOpen, setIsPayFailModalOpen] = useState(false);
  // Session Timeout modal
  const [isPayTimeoutModalOpen, setIsPayTimeoutModalOpen] = useState(false);
  //验证码 图片 验证码
  const [codePic, setCodePic] = useState("");
  const [code, setCode] = useState("");

  useEffect(() => {
    setIsPayFailModalOpen(true);
    setIsPayTimeoutModalOpen(true);
  }, []);

  const getCodeData = () => {
    getGenerateCodeAndPic()
      .then((data) => {
        console.log(data, "data");
        //@ts-ignore
        setCodePic(data.codePic);
        //@ts-ignore
        setCode(data.code || "");
      })
      .catch((error) => {
        console.error("Error fetching code and picture:", error);
      });
  };
  useEffect(() => {
    getCodeData();
  }, []);
  // 验证码验证码生成以下
  const [verificationCode, setVerificationCode] = useState("");

  // 在组件挂载时生成一个验证码

  // speak Code
  const speakCode = () => {
    code.split(",").forEach((digit) => {
      const utterance = new SpeechSynthesisUtterance(digit); // 创建语音合成实例
      // utterance.lang = 'zh-CN'; // 设置语言为中文，依据需要可以调整
      speechSynthesis.speak(utterance); // 播放语音
    });
    // const utterance = new SpeechSynthesisUtterance(code);
    // speechSynthesis.speak(utterance);
  };
  // 验证码验证码生成以上

  const handleBtnOk = () => {
    // 判断验证码输入正确否
    if (verificationCode === code) {
      setIsConfirmModalOpen(true);
    } else {
      message.error("Type the characters above is error！");
    }
  };

  const handleBtnCancel = () => {
    history.back();
  };

  const handleConfirmModalOk = () => {
    getCreateBooking({
      //test
      userId,
      lpnId: bookingDataRes?.lpnNo || "tt",
      tariffId: bookingDataRes?.bookingId || "222",
      comId: "222",
      pymPrice: bookingDataRes?.pymPrice || "178",
      startDate: bookingDataRes?.startDate || "2024-10-23",
      //@ts-ignore
      duration: bookingDataRes?.duration || "7",
      // @ts-ignore根据什么页面来判断
      passType: bookingDataRes?.passType || "DAILY",
    });
    history.push("/monthly-booking/success");
  };

  const handleConfirmModalCancel = () => {
    setIsConfirmModalOpen(false);
  };

  const handlePayFailModalOk = () => {
    setIsPayFailModalOpen(false);

    // call payment api
  };

  const handleTimeoutModalOk = () => {
    setIsPayTimeoutModalOpen(false);
    // repeat login
    login("");
  };

  const onFinish = () => {
    console.log("倒计时结束");
  };
  return (
    <PaddingContent className="payment-info">
      <CustomTitle>Payment Information</CustomTitle>
      <ContentBorder>
        <div className="payment-header">
          <span className="confirm-tips">
            Please confirm your booking information
          </span>
          <div className="time-left">
            <span className="time-left-tips">Time left for submit booking</span>
            <div className="count-down">
              <img src={Time} alt="svg" />
              <CountDown
                style={CountDownSytle}
                format={formatTime}
                target={targetTime}
                onEnd={onFinish}
              />
            </div>
          </div>
        </div>
        <CustomSubTitle>Basic Information</CustomSubTitle>
        <Descriptions
          layout="vertical"
          labelStyle={LabelStyle}
          contentStyle={ContentStyle}
          column={3}
        >
          <Descriptions.Item
            label="Surname (English)"
            style={{ paddingBottom: 0 }}
          >
            LAM
          </Descriptions.Item>
          <Descriptions.Item label="Given Name (English)">
            YAN
          </Descriptions.Item>
          <Descriptions.Item label="Name (Chinese) ">-</Descriptions.Item>
          <Descriptions.Item label="Email ">
            lamyanting@hkaa.com
          </Descriptions.Item>
          <Descriptions.Item label="Mobile">+852 9221 1024</Descriptions.Item>
          <Descriptions.Item label="Company">
            Airport Authority Hong Kong
          </Descriptions.Item>
        </Descriptions>
        <StyledDivider plain />
        <CustomSubTitle>Booking Information</CustomSubTitle>
        <Descriptions
          layout="vertical"
          labelStyle={LabelStyle}
          contentStyle={ContentStyle}
          column={4}
        >
          <Descriptions.Item label="Vehicle Type">
            {bookingDataRes?.vehType || "Private Car"}
          </Descriptions.Item>
          <Descriptions.Item label="License Plate Number">
            {bookingDataRes?.lpnNo || "AC123"}
          </Descriptions.Item>
          <Descriptions.Item label="Octopus No.">
            {" "}
            {bookingDataRes?.octopus || "70000111"}{" "}
          </Descriptions.Item>
          <Descriptions.Item label="Car Park">
            {bookingDataRes?.carParkEnName || "Car Park 1"}{" "}
          </Descriptions.Item>
          <Descriptions.Item label="Parking Period">
            {bookingDataRes?.duration || period}
          </Descriptions.Item>
          <Descriptions.Item label="Eligible Month">
            October 2024
          </Descriptions.Item>
        </Descriptions>
        <StyledDivider plain />
        <CustomSubTitle>Payment Information</CustomSubTitle>
        <div className="booking-fee">
          <span className="unit-fee">Car Park Booking Fee</span>
          <span className="unit-fee-values">
            {" "}
            HK${bookingDataRes?.pymPrice || pymPrice}
          </span>
        </div>
        <div className="booking-discount">
          <span className="discount">DPP Permit Discount</span>
          <span className="discount-values">{-dpppPrice}</span>
        </div>
        <div className="booking-total-amount">
          <span className="total-amount">Total Amount</span>
          <span className="total-amount-values">
            HK${bookingDataRes?.pymPrice || calculatedCost}
          </span>
        </div>
        <StyledDivider plain />
        <div className="auth-code">
          <span className="auth-by-visual">Authentication By Visual</span>
          <div className="auth-code-content">
            <p className="code">
              {/* {generatedCode} */}
              <img src={codePic} alt="code" />
            </p>
            <Space size={16}>
              <Button className="code-btn" onClick={speakCode}>
                <img src={Sound} alt="svg" />
              </Button>
              <Button className="code-btn" onClick={getCodeData}>
                <img src={Resend} alt="svg" />
              </Button>
            </Space>
          </div>
          <div className="type-characters">
            <span className="type-characters-text">
              Type the characters above
            </span>
            <ProFormText
              className="input-number"
              width="xs"
              fieldProps={{
                required: true,
                value: verificationCode,
                onChange: (e) => setVerificationCode(e.target.value),
              }}
            />
          </div>
        </div>

        <StyledDivider plain />
        <ProFormCheckbox name="a">
          <div className="checkbox-content">
            Please read and agree to our
            <span className="highlight-text"> Terms and Conditions </span>
            before submission.
          </div>
          {/* <DynamicCaptcha /> */}
        </ProFormCheckbox>

        <StyledTextAlign>
          <Space size={"middle"}>
            <StyledCancel
              onClick={handleBtnCancel}
              type="default"
              size={"middle"}
            >
              Cancel
            </StyledCancel>
            <StyledAgree onClick={handleBtnOk} type="default" size={"middle"}>
              Confirm to Pay
            </StyledAgree>
          </Space>
        </StyledTextAlign>
      </ContentBorder>

      {/*Confirm to Pay  */}
      <CustomModal
        width="40%"
        icon={AlertFill}
        title="Confirm to Pay?"
        onOk={handleConfirmModalOk}
        onCancel={handleConfirmModalCancel}
        isModalOpen={isConfirmModalOpen}
        btnLeftText="Cancel"
        btnRightText="Confirm"
      />
      {isShowPayFailModal === "fail" && (
        <CustomModal
          width="40%"
          icon={AlertFill}
          title="Payment Failure"
          content="Your payment could not be processed. Please check your payment details and try again."
          onOk={handlePayFailModalOk}
          isModalOpen={isPayFailModalOpen}
          btnRightText="Back to Payment"
          displayCancelBtnFooter="none"
        />
      )}
      {isShowPayFailModal === "timeout" && (
        <CustomModal
          width="40%"
          icon={AlertFill}
          title="Session Timeout"
          content="Your session has expired due to inactivity. Please log in again to continue."
          onOk={handleTimeoutModalOk}
          isModalOpen={isPayTimeoutModalOpen}
          btnRightText="Log In Now"
          displayCancelBtnFooter="none"
        />
      )}
    </PaddingContent>
  );
};

export default PaymentInfo;
